package com.syg.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author syg
 * @date 2021年11月25日19:05:46
 * @version 1.0
 */
@RestController
public class TestEnv {
    Logger log = LoggerFactory.getLogger(TestEnv.class);

    @Resource
    ConfigurableEnvironment environment;

    /**
     * 测试环境变量
     * @return
     */
    @RequestMapping("/testEnv")
    public void testEnv() {
        // spring.application.name是在application.yml文件中配置的,默认的为空,配置以后就可以获取了
        System.out.println(environment.getProperty("spring.application.name"));

        // 配置文件加在完毕以后,再次加载新的文件
        MutablePropertySources propertySources = environment.getPropertySources();
        String pathObj = environment.getProperty("syg.boot.core.ymlResourcePath", String.class, null);
        load(propertySources, pathObj);
    }

    private void load(MutablePropertySources propertySources, String path) {
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        Object envList = new ArrayList<>();

        try {
            log.info("^_^加载自定义YML文件，当前文件路径:" + path + "^_^");
            envList = loader.load(path, new ClassPathResource(path));
        } catch (IOException var6) {
            log.error("path:{}不存在请确认！", path);
        } catch (Throwable var7) {
            log.error("path:{}不存在请确认！！", path);
        }

        if (!StringUtils.isEmpty((List)envList)) {
            propertySources.addLast((PropertySource)((List)envList).get(0));
        }

    }
}
